﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TimerManager : Singleton<TimerManager> {

	private List<Timer> m_timers;

	private int m_timerSequence;

	public override void Init () {
		this.m_timers = new List<Timer> ();
		this.m_timerSequence = 0;
	}

	public void Update () {
		int i = 0;
		while (i < m_timers.Count) {
			if (m_timers[i].IsFinished ()) {
				m_timers.RemoveAt (i);
			} else {
				m_timers[i].Update ((int) (Time.deltaTime * 1000));
				i++;
			}
		}
	}

	public int AddTimer (float time, System.Action callback) {
		return AddTimer ((int) (time * 1000), 1, (seq) => {
			if (callback != null)
				callback ();
		});
	}

	public int AddTimer (int time, int loop, Timer.OnTimeUpHandler onTimeUpHandler) {
		this.m_timerSequence++;
		this.m_timers.Add (new Timer (time, loop, onTimeUpHandler, this.m_timerSequence));
		return this.m_timerSequence;
	}

	public void RemoveTimer (int sequence) {
		for (int j = 0; j < m_timers.Count; j++) {
			if (m_timers[j].IsSequenceMatched (sequence)) {
				m_timers[j].Finish ();
				return;
			}
		}
	}

	public void RemoveTimerSafely (ref int sequence) {
		if (sequence != 0) {
			this.RemoveTimer (sequence);
			sequence = 0;
		}
	}

	public void PauseTimer (int sequence) {
		Timer timer = this.GetTimer (sequence);
		if (timer != null) {
			timer.Pause ();
		}
	}

	public void ResumeTimer (int sequence) {
		Timer timer = this.GetTimer (sequence);
		if (timer != null) {
			timer.Resume ();
		}
	}

	public void ResetTimer (int sequence) {
		Timer timer = this.GetTimer (sequence);
		if (timer != null) {
			timer.Reset ();
		}
	}

	public void ResetTimerTotalTime (int sequence, int totalTime) {
		Timer timer = this.GetTimer (sequence);
		if (timer != null) {
			timer.ResetTotalTime (totalTime);
		}
	}

	public float GetTimerCurrent (int sequence) {
		Timer timer = this.GetTimer (sequence);
		if (timer != null) {
			return timer.CurrentTime;
		}
		return -1f;
	}

	public int GetLeftTime (int sequence) {
		Timer timer = this.GetTimer (sequence);
		if (timer != null) {
			return timer.GetLeftTime () / 1000;
		}
		return -1;
	}

	public Timer GetTimer (int sequence) {
		for (int j = 0; j < m_timers.Count; j++) {
			if (m_timers[j].IsSequenceMatched (sequence)) {
				return m_timers[j];
			}
		}
		return null;
	}

	public void RemoveTimer (Timer.OnTimeUpHandler onTimeUpHandler) {
		for (int i = 0; i < m_timers.Count; i++) {
			if (m_timers[i].IsDelegateMatched (onTimeUpHandler)) {
				m_timers[i].Finish ();
			}
		}
	}

	public void RemoveAllTimer () {
		this.m_timers.Clear ();
	}
}